package com.jic.order.controller.manage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.manager.api.rest.ManagerMerchantApi;
import com.jic.manager.request.MerchantRequest;
import com.jic.order.entity.OrderFreightTemplate;
import com.jic.order.entity.OrderFreightTemplateItem;
import com.jic.order.manage.request.OrderFreightTemplateEditRequest;
import com.jic.order.manage.request.OrderFreightTemplateRequest;
import com.jic.order.manage.response.OrderFreightTemplateItemResponse;
import com.jic.order.manage.response.OrderFreightTemplateResponse;
import com.jic.order.service.OrderFreightTemplateItemService;
import com.jic.order.service.OrderFreightTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 订单运费模板
 *
 * */
@Slf4j
@Api(value = "订单运费模板", tags = {"订单运费模板"})
@RequestMapping(value = "orderFreightTemplate")
@RestController
public class OrderFreightTemplateController {

	@Autowired
	OrderFreightTemplateService orderFreightTemplateService;
	@Autowired
	OrderFreightTemplateItemService orderFreightTemplateItemService;
	@Resource
	private ManagerMerchantApi managerMerchantApi;


	@ApiOperation(value = "获取所有订单运费模板信息")
	@ResponseBody
	@PostMapping(value = "/queryPage")
	public RestResult<PageResult<OrderFreightTemplateResponse>> queryPage(@RequestBody OrderFreightTemplateRequest form) {
		log.info("开始调用订单运费分页，{}", JSON.toJSONString(form));
		Page page = new Page();
		page.setLimit(form.getLimit());
		page.setStart(form.getStart());
		OrderFreightTemplate orderFreightTemplate = new OrderFreightTemplate();
		BeanUtils.copyProperties(form, orderFreightTemplate);
		DeptTypeEnums deptType = form.getAdminOperate().getDeptType();
		if (deptType.getCode() != 0) {
			orderFreightTemplate.setDeptId(form.getDeptId());
		}
		PageResult<OrderFreightTemplate> result = orderFreightTemplateService.queryPage(orderFreightTemplate, page);
		List<OrderFreightTemplateResponse> orderFreightTemplateResponses = result.getRows().stream().map(temp -> {
			//查询自定义模板和默认模板条目
			OrderFreightTemplateResponse orderFreightTemplateResponse = new OrderFreightTemplateResponse();
			BeanUtils.copyProperties(temp, orderFreightTemplateResponse);
			OrderFreightTemplateItem orderFreightTemplateItem = new OrderFreightTemplateItem();
			orderFreightTemplateItem.setFreightTemplateId(orderFreightTemplateResponse.getId());
			orderFreightTemplateItem.setType(1);
			List<OrderFreightTemplateItemResponse> orderFreightTemplateItemResponseList = orderFreightTemplateItemService.query(orderFreightTemplateItem);
			List<JSON> freightRule = new LinkedList<>();
			for (OrderFreightTemplateItemResponse orderFreightTemplateItemResponse : orderFreightTemplateItemResponseList) {
				JSONObject freightRuleJSON = JSONObject.parseObject(orderFreightTemplateItemResponse.getFreightRule());
				freightRuleJSON.put("deliveryCode", "快递物流");
				freightRule.add(freightRuleJSON);
			}
			orderFreightTemplateResponse.setFreightRuleList(freightRule);
			orderFreightTemplateResponse.setOrderFreightTemplateItemResponseList(orderFreightTemplateItemResponseList);
			//查询是否存在指定包邮模板
			OrderFreightTemplateItem orderFreightTemplateItemShipping = new OrderFreightTemplateItem();
			orderFreightTemplateItemShipping.setFreightTemplateId(orderFreightTemplateResponse.getId());
			orderFreightTemplateItemShipping.setType(2);
			List<OrderFreightTemplateItemResponse> orderFreightTemplateItemResponseShippingList = orderFreightTemplateItemService.query(orderFreightTemplateItemShipping);
			if (orderFreightTemplateItemResponseShippingList.size() == 0) {
				orderFreightTemplateResponse.setIsShipping(false);
			} else {
				for (OrderFreightTemplateItemResponse orderFreightTemplateItemShippingResponse : orderFreightTemplateItemResponseShippingList) {
					orderFreightTemplateItemShippingResponse.setUnderUnit(JSONObject.parseObject(orderFreightTemplateItemShippingResponse.getFreightRule()).getLongValue("underUnit"));
					orderFreightTemplateItemShippingResponse.setUnderUnitCost(JSONObject.parseObject(orderFreightTemplateItemShippingResponse.getFreightRule()).getLongValue("underUnitCost"));
				}
				orderFreightTemplateResponse.setShippingFreightTemplateItemResponseList(orderFreightTemplateItemResponseShippingList);
				orderFreightTemplateResponse.setIsShipping(true);
			}
			if(null != temp.getDeptId()){
				RestResult<List<MerchantRequest>> merchantList = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
					add(Long.valueOf(temp.getDeptId()));
				}});
				if(CollectionUtils.isNotEmpty(merchantList.getData())){
					orderFreightTemplateResponse.setMerchantName(merchantList.getData().get(0).getName());
				}
			}
			return orderFreightTemplateResponse;
		}).filter(item -> item != null).collect(Collectors.toList());
		PageResult<OrderFreightTemplateResponse> pageResult = new PageResult<>();
		pageResult.setRows(orderFreightTemplateResponses);
		pageResult.setTotal(result.getTotal());
		return RestResult.success(pageResult);

	}

	@ApiOperation("订单运费模板  新增编辑")
	@ResponseBody
	@PostMapping(value = "/editOrderFreightTemplate")
	public RestResult editOrderFreightTemplate(@RequestBody OrderFreightTemplateEditRequest orderFreightTemplateEditRequest) {
		log.info("开始调用订单运费模板新增编辑，{}", JSON.toJSONString(orderFreightTemplateEditRequest));
		//TODO 将merchantId存入deptId
		orderFreightTemplateEditRequest.setDeptId(orderFreightTemplateEditRequest.getMerchantId());
		RestResult restResult = new RestResult<>();
		try {
			if (orderFreightTemplateEditRequest.getId() != null) {
				restResult = orderFreightTemplateService.update(orderFreightTemplateEditRequest);
			} else {
				restResult = orderFreightTemplateService.insert(orderFreightTemplateEditRequest);
			}

		} catch (Exception e) {
			log.error("editOrderFreightTemplate========》", e);
		}
		return restResult;

	}

	@ApiOperation("订单运费模板 删除")
	@ResponseBody
	@PostMapping(value = "/deleteOrderFreightTemplate")
	public RestResult deleteOrderFreightTemplate(@RequestBody OrderFreightTemplateRequest orderFreightTemplatetRequest) {
		log.info("开始调用订单运费模板删除，{}", JSON.toJSONString(orderFreightTemplatetRequest));
		RestResult restResult = new RestResult<>();
		try {
			restResult = orderFreightTemplateService.delete(orderFreightTemplatetRequest.getId());

		} catch (Exception e) {
			log.error("editOrderFreightTemplate========》", e);
		}
		return restResult;

	}

	@ApiOperation("设置订单运费模板")
	@ResponseBody
	@PostMapping(value = "/setOrderFreightTemplateDefault")
	public RestResult setOrderFreightTemplateDefault(@RequestBody OrderFreightTemplateRequest orderFreightTemplatetRequest) {
		log.info("开始调用订单设置订单运费模板，{}", JSON.toJSONString(orderFreightTemplatetRequest));
		RestResult restResult = new RestResult<>();
		try {
			restResult = orderFreightTemplateService.setDefault(orderFreightTemplatetRequest.getId());

		} catch (Exception e) {
			log.error("setOrderFreightTemplateDefault========》", e);
		}
		return restResult;

	}

	@ApiOperation("查询订单运费条目")
	@ResponseBody
	@PostMapping(value = "/queryOrderFreightTemplate")
	public RestResult<List<OrderFreightTemplateResponse>> queryOrderFreightTemplate() {
		log.info("开始调用订单设置订单运费模板，{}");
		List<OrderFreightTemplateResponse> orderFreightTemplateResponseList = new ArrayList<OrderFreightTemplateResponse>();
		try {
			OrderFreightTemplate orderFreightTemplate = new OrderFreightTemplate();
			List<OrderFreightTemplate> orderFreightTemplateList = orderFreightTemplateService.query(orderFreightTemplate);
			orderFreightTemplateList.forEach(item -> {
				OrderFreightTemplateResponse orderFreightTemplateResponse = new OrderFreightTemplateResponse();
				orderFreightTemplateResponse.setId(item.getId());
				orderFreightTemplateResponse.setName(item.getName());
				orderFreightTemplateResponseList.add(orderFreightTemplateResponse);
			});

		} catch (Exception e) {
			log.error("queryOrderFreightTemplate========》", e);
		}
		return RestResult.success(orderFreightTemplateResponseList);
	}
}
